import { Body, Controller, Delete, Get, Post, Put, Query } from '@nestjs/common'
import { ApiOperation, ApiTags } from '@nestjs/swagger'

import { ApiResult } from '~/common/decorators/api-result.decorator'
import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator'
import { DeleteDto } from '~/common/dto/delete.dto'
import { BusinessException } from '~/common/exceptions/biz.exception'
import { CreatorPipe } from '~/common/pipes/creator.pipe'
import { UpdaterPipe } from '~/common/pipes/updater.pipe'
import { ErrorEnum } from '~/constants/error-code.constant'
import { Pagination } from '~/helper/paginate/pagination'
import { definePermission, Perm } from '~/modules/system/auth/decorators/permission.decorator'
import { PostEntity } from '~/modules/system/post/post.entity'

import { PostQueryDto, PostSaveDto, PostSimpleDto } from './post.dto'
import { PostService } from './post.service'

export const permissions = definePermission('system:post', {
  PAGE: 'page',
  QUERY: 'query',
  CREATE: 'create',
  UPDATE: 'update',
  DELETE: 'delete',
} as const)

@ApiSecurityAuth()
@ApiTags('System - 岗位模块')
@Controller('post')
export class PostController {
  constructor(private postService: PostService) {}

  @Get('page')
  @ApiOperation({ summary: '获取岗位分页列表' })
  @ApiResult({ type: [PostEntity], isPage: true })
  @Perm(permissions.PAGE)
  async page(@Query() dto: PostQueryDto): Promise<Pagination<PostEntity>> {
    return this.postService.page(dto)
  }

  @Get('list')
  @ApiOperation({ summary: '获取岗位列表' })
  @ApiResult({ type: [PostEntity] })
  async list(@Query() dto: PostQueryDto): Promise<PostEntity[]> {
    return this.postService.list(dto)
  }

  @Get('simple-list')
  @ApiOperation({ summary: '获取岗位简单列表' })
  @ApiResult({ type: [PostSimpleDto] })
  async simpleList(): Promise<PostSimpleDto[]> {
    return this.postService.getSimpleList()
  }

  @Get('get')
  @ApiOperation({ summary: '查询岗位详情' })
  @ApiResult({ type: PostEntity })
  @Perm(permissions.QUERY)
  async get(@Query('id') id: number): Promise<PostEntity> {
    return this.postService.findOne(id)
  }

  @Post('create')
  @ApiOperation({ summary: '创建岗位' })
  @Perm(permissions.CREATE)
  async create(@Body(CreatorPipe) dto: PostSaveDto): Promise<void> {
    await this.postService.create(dto)
  }

  @Put('update')
  @ApiOperation({ summary: '更新岗位' })
  @Perm(permissions.UPDATE)
  async update(@Body(UpdaterPipe) dto: PostSaveDto): Promise<void> {
    if (!dto.id) {
      throw new BusinessException(ErrorEnum.REQUESTED_RESOURCE_NOT_FOUND)
    }
    await this.postService.update(dto.id, dto)
  }

  @Delete('delete')
  @ApiOperation({ summary: '删除单个岗位' })
  @Perm(permissions.DELETE)
  async delete(@Query('id') id: number): Promise<void> {
    if (!id || Number.isNaN(id)) {
      throw new BusinessException(ErrorEnum.REQUESTED_RESOURCE_NOT_FOUND)
    }

    // 查询是否有关联用户，如果含有则无法删除
    const count = await this.postService.countUsersByPostId(id)
    if (count > 0) {
      throw new BusinessException(ErrorEnum.DEPARTMENT_HAS_ASSOCIATED_USERS) // 复用错误码
    }

    await this.postService.delete(id)
  }

  @Delete('delete-list')
  @ApiOperation({ summary: '批量删除岗位' })
  @Perm(permissions.DELETE)
  async deleteList(@Query() dto: DeleteDto): Promise<void> {
    // 解析ids参数
    const ids = dto.ids.split(',').map(id => Number.parseInt(id.trim())).filter(id => !Number.isNaN(id))

    if (ids.length === 0) {
      throw new BusinessException(ErrorEnum.REQUESTED_RESOURCE_NOT_FOUND)
    }

    // 批量删除
    for (const id of ids) {
      // 查询是否有关联用户，如果含有则无法删除
      const count = await this.postService.countUsersByPostId(id)
      if (count > 0) {
        throw new BusinessException(ErrorEnum.DEPARTMENT_HAS_ASSOCIATED_USERS) // 复用错误码
      }

      await this.postService.delete(id)
    }
  }
}
